package cn.cors;


import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;

/**
 * 类简介:Cors 过滤器
 * 注意：
 *  1.如果添加多个相同Cors配置，那么以最后一个为准
 *  2.本类针未对多个Cors配置进行逻辑判断
 *  如果有无法满足的逻辑运算，请在本类的基础上添加
 *
 * @Author: ShangGuan
 * @Time: 2024/05/29
 **/
public class CorsFilter implements Filter {

    private final LinkedList<Cors> cors;

    public CorsFilter(LinkedList<Cors> cors) {
        this.cors = cors;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        if (!CollectionUtils.isEmpty(cors)) {
            //配置cors
            for (Cors cors : cors) {
                CorsConfig corsConfig = new CorsConfig(cors);
                httpServletResponse = corsConfig.setHttpCors((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}